<?php

namespace app\api\service;

use Psr\SimpleCache\InvalidArgumentException;
use think\cache\Driver;
use think\facade\Cache;

class RedisLock
{
    private string $key;
    private Driver $redis;

    public function __construct(string $key)
    {
        $this->key   = $key;
        $this->redis = Cache::store('redis');
    }

    /**
     * 获得锁
     * @param int $expire_time
     * @return bool
     * @throws InvalidArgumentException
     */
    public function getLock(int $expire_time = 1): bool
    {
        $expire    = $expire_time;
        $lockValue = time() + $expire;
        $lock      = $this->redis->setNx($this->key, $lockValue);
        if (!empty($lock) || ($this->redis->get($this->key) < time() && $this->redis->getSet($this->key, $lockValue) < time())) {
            $this->redis->expire($this->key, $lockValue);
            return true;
        }
        return false;
    }

    /**
     * 删除锁
     * @return bool
     * @throws InvalidArgumentException
     */
    public function delLock(): bool
    {
        if ($this->redis->ttl($this->key)) {
            $this->redis->delete($this->key);
        }
        return true;
    }
}